package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sk.cardeal.R;
import com.sk.cardeal.act.settlement.SettlementActivity;
import com.sk.cardeal.adapter.PicAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.SpecialEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.utils.UpLoadUtils;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sk on 2018/4/19.
 */

public class SpecialBuyActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, HandleDataCallBack {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.ed_vin)
    EditText edVin;
    @BindView(R.id.pic_ryc)
    RecyclerView picRyc;
    @BindView(R.id.ed_note)
    EditText edNote;
    @BindView(R.id.apply)
    TextView apply;
    private LoadingDialog loadingDialog;

    private List<LocalMedia> allDataList = new ArrayList<>();
    private List<LocalMedia> pictureList = new ArrayList<>();
    private PicAdapter adapter;
    private int count;
    private StringBuilder sb = new StringBuilder();
    private String url;
    private String cardId;
    private String vin;
    private SpecialEntity specialEntity;

    @Override
    protected int getContentView() {
        return R.layout.activity_special_buy;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        specialEntity = new SpecialEntity();

        titleView.setMyCallBack(this);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        cardId = getIntent().getStringExtra("id");
        vin = getIntent().getStringExtra("vin");
        edVin.setText(vin);

        specialEntity.setCarId(cardId);
        specialEntity.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
        specialEntity.setApplyUser(MyUtils.getUser(mContext).getId());
        specialEntity.setCode(MyUtils.getRndNumCode());

        allDataList.add(new LocalMedia());
        picRyc.setLayoutManager(new GridLayoutManager(this, 5));
        adapter = new PicAdapter(R.layout.item_release_pic, allDataList);
        picRyc.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i){
            case 1:
                finish();
                break;
        }
    }

    @OnClick(R.id.apply)
    public void onViewClicked() {
        if (TextUtils.isEmpty(edVin.getText().toString())) {
            SnackUtils.showError(mRootView, "请输入车架号！");
            return;
        }

        if (allDataList.size() == 0) {
            SnackUtils.showError(mRootView, "请至少上传一张图片！");
            return;
        }

        specialEntity.setCarVin(edVin.getText().toString());
        specialEntity.setNotes(edNote.getText().toString());
        if (pictureList.size() > 0) {
            loadingDialog.show();
            count = 1;
            if (pictureList.get(0).isCompressed()) {
                UpLoadUtils.uploadPicTask(pictureList.get(0).getCompressPath(), SpecialBuyActivity.this);
            } else {
                UpLoadUtils.uploadPicTask(pictureList.get(0).getPath(), SpecialBuyActivity.this);
            }

        } else {
            Toast.makeText(mContext, "您尚未选择上传的图片！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (position == allDataList.size() - 1) {
            PictureSelector.create(SpecialBuyActivity.this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(9)// 最大图片选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .compressSavePath(Environment.getExternalStorageDirectory().getPath())//压缩图片保存地址
                    .selectionMedia(pictureList)// 是否传入已选图片 List<LocalMedia> list
                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                    .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    try {
                        // 图片选择结果回调
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                        pictureList.clear();
                        pictureList.addAll(selectList);
                        allDataList.clear();
                        allDataList.addAll(pictureList);
                        allDataList.add(new LocalMedia());
                        adapter.notifyDataSetChanged();
                        break;
                    } catch (Exception e) {
                        Log.e("onActivityResult", e.toString());
                    }

            }
        }
    }

    @Override
    public void success(final String path) {
        super.success(path);
        Log.v("success", path);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (count == pictureList.size()) {
                    loadingDialog.cancelDialog();
                    Log.v("success", path);
                    sb.append(path);
                    Intent intent = new Intent();
                    if (url != null && url.length() > 0) {
                        intent.putExtra("url", url + "," + sb.toString());
                        pictureList.clear();
                        intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) pictureList);
                    } else {
                        intent.putExtra("url", sb.toString());
                        pictureList.clear();
                        intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) pictureList);
                    }
                    specialEntity.setPicUrl(sb.toString());
                    loadingDialog.show();
                    AppApi.saveSpecialBuy(specialEntity, SpecialBuyActivity.this, 0, SpecialBuyActivity.this);
                } else {
                    sb.append(path).append(",");
                    count++;
                    if (pictureList.get(count - 1).isCompressed()) {
                        UpLoadUtils.uploadPicTask(pictureList.get(count - 1).getCompressPath(), SpecialBuyActivity.this);
                    } else {
                        UpLoadUtils.uploadPicTask(pictureList.get(count - 1).getPath(), SpecialBuyActivity.this);
                    }

                }
            }
        });


    }

    @Override
    public void fail() {
        super.fail();
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        Toast.makeText(mContext,"缺件采购申请，提交成功！",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }
}
